package linkedlist.other;

import linkedlist.Node;
import linkedlist.create.LoopLinkedCreator;
import linkedlist.iterator.LoopIterator;

import java.util.Arrays;

/**
 * @Author wangtengyu
 * @Create 2018-09-11-9:57 删除排序链表中的重复节点，重复的全部删除掉 如果当前节点不为null，判断当前节点是否与下一个节点的值相同，如果相同，再判断再下一个节点。
 * //针对头节点的判断
 *
 * 解题思路
 */
public class DeleteRepeatNode {

  /**
   * 删除重复节点，重复的全删除
   */
  public Node deleteRepeatNode(Node head) {
    if (head == null) {
      return null;
    }
    //定义前一个节点的指针
    Node<Integer> prev = null;
    //定义现在节点的指针
    Node<Integer> now = head;

    while (now != null) {//遍历
      Node<Integer> next = now.getNext();
      if (next != null && next.getData() == now.getData()) {//找到重复
        //获取到重复的这个值
        int value = now.getData();
        //判断接下来的节点是不是也是重复的 如果为null或者值不同就可以了
        while (next != null && next.getData() == value) {
          next = next.getNext();
        }
        //如果删除的是头节点
        if (prev == null) {
          head = next;
        } else {
          prev.setNext(next);
        }
        now = next;

      } else {
        //未找到重复，节点往下移动
        prev = now;
        now = now.getNext();
      }
    }
    return head;
  }


  /**
   * 删除重复节点，重复的保留一个
   */
  public Node deleteRepeatNode2(Node head) {
    if (head == null) {
      return null;
    }
    Node now = head;
    while (now != null) {
      Node<Integer> next = now.getNext();
      if (next != null && next.getData() == now.getData()) {
        int value = next.getData();
        while (next != null && next.getData() == value) {
          next = next.getNext();
        }
        now.setNext(next);
        now = next;
      } else {
        now = now.getNext();
      }
    }
    return head;
  }

  public static void main(String[] args) {
    LoopLinkedCreator creator = new LoopLinkedCreator();
    DeleteRepeatNode deletor = new DeleteRepeatNode();
    LoopIterator iterator = new LoopIterator();
    Node node = creator.createlinkedList(Arrays.asList(1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 8));
    node = deletor.deleteRepeatNode(node);
    iterator.iterator(node);
  }
}
